﻿using Modbus.Data;
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace My_modbus_slave
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.AddRange(SerialPort.GetPortNames());

        }
        int i = 0;
        bool isChange = true;
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = i.ToString();
            i++;
            isChange = true;
            Task.Run(() => { StartModbusSerialRtuSlave(); });
            Thread.Sleep(2000);
            
            Task.Run(() => { 

                            ModbusDataCollection<ushort>  data= slave.DataStore.HoldingRegisters;
                while (isChange)
                {
                    data[2] += 1;
                    Thread.Sleep(2000);
                    if (data[2] > 1000)
                        data[2] = 0;
                                } 
                            });
            
        }
        private ModbusSerialSlave slave;
        private SerialPort slavePort;
        public  void StartModbusSerialRtuSlave()
        {
            slavePort = new SerialPort("COM2")
            {
                BaudRate = 9600,
                DataBits = 8,
                Parity = Parity.None,
                StopBits = StopBits.One
            };
            slavePort.Open();

                byte unitId = 20;


                slave= ModbusSerialSlave.CreateRtu(unitId, slavePort);
                slave.DataStore = DataStoreFactory.CreateDefaultDataStore();
                slave.WriteComplete += Slave_WriteComplete;
                slave.Listen();
                
            
        }

        private void Slave_WriteComplete(object sender, ModbusSlaveRequestEventArgs e)
        {
           ModbusDataCollection<ushort> myarray= slave.DataStore.HoldingRegisters;
            System.Console.WriteLine(myarray.Count);
           for (int i =0; i < 13; i++)
            {
                System.Console.WriteLine("HR-{0}: {1}", i, myarray[i]);
            }
            

         
        }

        private void button2_Click(object sender, EventArgs e)
        {
            isChange = false;
            slave.Dispose();
            slavePort.Close();
        }
    }
}
